<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="需求名称" prop="title">
        <el-input v-model="queryParams.searchWord" placeholder="请输入需求名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="行业领域" prop="industrySector">
        <el-select v-model="queryParams.industrySector" placeholder="请选择行业领域">
          <el-option v-for="item in industrySectorList" :key="item.label" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择审核状态">
          <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['kjy:demand:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate2"
          v-hasPermi="['kjy:demand:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['kjy:demand:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kjy:demand:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="demandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-width="110px" label-position="right" inline class="demand-table-expand">
            <el-form-item label="行业领域">
              <span>{{ props.row.industrySector }}</span>
            </el-form-item>
            <el-form-item label="所在地">
              <span>
                {{ props.row.location && props.row.location.join(" / ") }}
              </span>
            </el-form-item>
            <el-form-item v-if="props.row.state === -1" label="审核不通过原因">
              <span>{{ props.row.failedReason }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="需求名称" align="center" prop="title" />
      <el-table-column label="发布人" align="center" prop="authorName" />
      <el-table-column label="需求类型" align="center" prop="requirementType">
      </el-table-column>
      <el-table-column label="预算（万元）" align="center" prop="budget" />
      <el-table-column label="内容" align="center" prop="content">
        <template slot-scope="scope">
          <el-popover popper-class="my-popper" trigger="click" placement="top">
            <div v-html="scope.row.content"></div>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">点击查看</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="deadline">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.state === 0" type="warning">审核中</el-tag>
          <el-tag v-if="scope.row.state === -1" type="danger">未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kjy:demand:edit']">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['kjy:demand:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
      @pagination="getList" />

    <!-- 添加或修改需求对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="审核状态" prop="state">
          <el-radio v-model="form.state" :label="1">通过</el-radio>
          <el-radio v-model="form.state" :label="-1">不通过</el-radio>
        </el-form-item>
        <el-form-item v-if="form.state === -1" label="审核不通过原因" prop="failedReason">
          <el-input v-model="form.failedReason" placeholder="请输入审核不通过原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加需求对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="需求名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入需求名称"></el-input>
        </el-form-item>
        <el-form-item class="industry" label="行业领域" prop="industrySector">
          <el-select v-model="form.industrySector" multiple clearable placeholder="请选择行业领域">
            <el-option v-for="option in industrySectorList" :key="option.label" :label="option.label"
              :value="option.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="location" label="所在地" prop="location">
          <el-cascader v-model="form.location" :props="cityProps" :options="cityData"
            placeholder="请选择所在地"></el-cascader>
        </el-form-item>
        <el-form-item class="budget" label="投入预算（万元）" prop="budget">
          <el-input-number v-model="form.budget" :min="1" :max="5000" :step="10" :disabled="isNotConfirm"
            controls-position="right" placeholder="请输入投入预算"></el-input-number>
          <el-checkbox v-model="isNotConfirm">面议</el-checkbox>
        </el-form-item>
        <el-form-item label="需求类型" prop="requirementType">
          <el-radio-group v-model="form.requirementType">
            <el-radio label="设计">设计</el-radio>
            <el-radio label="开发">开发</el-radio>
            <el-radio label="咨询">咨询</el-radio>
            <el-radio label="其他">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="deadline" label="截止时间" prop="deadline">
          <el-date-picker v-model="form.deadline" value-format="yyyy-MM-dd" type="date" placeholder="请选择截止日期"
            :disabled-date="disabledBeforeDate" />
        </el-form-item>
        <el-form-item label="需求描述" prop="content">
          <div style="border: 1px solid #ccc">
            <!-- <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
              :mode="mode" /> -->
            <web-editor style="height: 230px; overflow-y: hidden" v-model="form.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="handleCreated" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDemand,
  getDemand,
  delDemand,
  addDemand,
  updateDemand,
} from "@/api/system/demand";
import { industrySectorList } from "@/data/industrySectorList";
import cityData from '@/data/cityData.json';
import { getToken } from '@/utils/auth'
import DOMPurify from 'dompurify';
//import Toolbar from './components/Toolbar.vue';
export default {
  name: "Demand",
  dicts: ["requirement_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 需求表格数据
      demandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        industrySector: null,
        location: null,
        budget: null,
        requirementType: null,
        author: null,
        authorName: null,
        title: null,
        content: null,
        deadline: null,
        releaseTime: null,
        state: null,
        failedReason: null,
        searchWord: null
      },
      // 表单参数
      form: {
        industrySector: [],
        location: [],
        budget: 10,
        requirementType: '',
        title: '',
        deadline: '',
        // 内容 HTML
        content: '',
      },
      cityProps: {
        value: 'name', // 指定选项的 值 为选项对象的某个属性值
        label: 'name', // 指定选项 标签 为选项对象的某个属性值
        children: 'children', //指定选项的 子选项 为选项对象的某个属性值
      },
      isNotConfirm: false,
      editorRef: null,
      toolbarConfig: {
        toolbarKeys: ['bold', 'italic', 'underline'],
        insertKeys: {
          index: 2,
          keys: ['link', 'image']
        },
        excludeKeys: ['undo', 'redo'],
        modalAppendToBody: true
      },
      mode: 'default',
      valueHtml: '',
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: '/api/file/upload',
            fieldName: 'file',
            maxFileSize: 100 * 1024 * 1024, // 100M
            maxNumberOfFiles: 100,
            allowedFileTypes: ['image/*'],
            metaWithUrl: false,
            headers: {
              Authorization: getToken(),
            },
            withCredentials: true,
            timeout: 5 * 1000, // 5 秒
            // customInsert(res, insertFn) {
            //   insertFn(res.data?.url, res.data?.name, '');
            // },
          },
        },
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '需求名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '需求名称长度不能超过100个字符', trigger: 'blur' }
        ],
        industrySector: [
          { required: true, message: '行业领域不能为空', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '所在地不能为空', trigger: 'change' }
        ],
        requirementType: [
          { required: true, message: '需求类型不能为空', trigger: 'blur' }
        ],
        deadline: [
          { required: true, message: '截止时间不能为空', trigger: 'change' }
        ],
        content: [
          // 富文本校验
          { required: true, validator: this.validateContent , trigger: 'change' },
        ],
        state: [
          { required: true, message: '审核状态不能为空', trigger: 'change' }
        ],
        failedReason: [
          { required: true, message: '审核不通过原因不能为空', trigger: 'blur' }
        ]
      },
      stateList: [
        { value: null, label: "全部" },
        { value: 0, label: "审核中" },
        { value: 1, label: "已通过" },
        { value: -1, label: "未通过" },
      ],
      industrySectorList: industrySectorList,
      cityData: cityData,
    };
  },

  created() {
    this.getList();
  },
  methods: {
    // 富文本内容校验方法
    validateContent(rule, value, callback) {
      // 去除HTML标签后的纯文本内容
      const strippedContent = value ? value.replace(/<[^>]+>/g, '').trim() : '';
      if (!value || strippedContent.length === 0) {
        callback(new Error('需求描述不能为空'));
      } else {
        callback();
      }
    },
    /** 查询需求列表 */
    getList() {
      this.loading = true;
      listDemand(this.queryParams).then((response) => {
        this.demandList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel2() {
      this.open2 = false;
      this.reset();
      this.valueHtml = null;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        industrySector: null,
        location: null,
        budget: null,
        requirementType: null,
        author: null,
        authorName: null,
        title: null,
        content: null,
        deadline: null,
        releaseTime: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        state: null,
        failedReason: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.searchWord = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open2 = true;
      this.title = "添加需求";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDemand(id).then((response) => {
        console.log("response:" + JSON.stringify(response));
        this.form = response.data;

        console.log("this.form:" + JSON.stringify(this.form));
        this.open = true;
        this.title = "审核需求";
      });
    },
    handleUpdate2(row) {
      this.reset();
      const id = row.id || this.ids;
      getDemand(id).then((response) => {
        console.log("response:" + JSON.stringify(response));
        this.form = response.data;

        console.log("this.form:" + JSON.stringify(this.form));
        this.open2 = true;
        this.title = "修改需求";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDemand(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDemand(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitForm2() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deadline !== null && !this.form.deadline.includes(' 23:59:59')) {
            this.form.deadline += ' 23:59:59';
          }
          if (this.form.id != null) {
            updateDemand(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open2 = false;
              this.getList();
            });
          } else {
            addDemand(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open2 = false;
              this.getList();
              this.valueHtml = null;
            });
          }
        }
      });
    },
    // 设置不能选择之前的时间
    disabledBeforeDate(date) {
      const today = new Date();
      today.setDate(today.getDate());
      return date < today;
    },
    handleCreated(editor) {
      editorRef.value = editor; // 记录 editor 实例，重要！
    },
    //editorRef: shallowRef(),
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount() {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    },
    useEditorConfig() {
      const editorConfig = {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: '/api/file/upload',
            fieldName: 'file',
            maxFileSize: 100 * 1024 * 1024, // 100M
            maxNumberOfFiles: 100,
            allowedFileTypes: ['image/*'],
            metaWithUrl: false,
            headers: {
              Authorization: getToken(),
            },
            withCredentials: true,
            timeout: 5 * 1000, // 5 秒
            customInsert(res, insertFn) {
              insertFn(res.data?.url, res.data?.name, '');
            },
          },
        },
      };
      return { editorConfig };
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除所选的需求？")
        .then(function () {
          return delDemand(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download(
    //     "kjy/demand/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `demand_${new Date().getTime()}.xlsx`
    //   );
    // },
  },
};
</script>
<style>
/* 表格展开样式 */
.demand-table-expand {
  font-size: 0;
  padding: 0 10%;
}

.demand-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demand-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
